﻿using System.Threading.Tasks;
using IdentityServer4.Configuration;
using IdentityServer4.Stores;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using Xms.Abp.Domain;

namespace IdentityServerManagement.Clients
{
    public class ClientStore : XmsDomainService, IClientStore
    {
        protected IClientRepository ClientRepository => LazyInject<IClientRepository>();
        protected IIdentityServerCacheContext IdentityServerCacheContext => LazyInject<IIdentityServerCacheContext>();
        protected IdentityServerOptions Options => LazyInject<IOptions<IdentityServerOptions>>().Value;

        public virtual async Task<IdentityServer4.Models.Client> FindClientByIdAsync(string clientId)
        {
            return await GetCacheItemAsync(clientId);
        }

        protected virtual async Task<IdentityServer4.Models.Client> GetCacheItemAsync(string clientId)
        {
            return await IdentityServerCacheContext.Clients.GetOrAddAsync(clientId, async () =>
                {
                    var client = await ClientRepository.FindByClientIdAsync(clientId);
                    return ObjectMapper.MapTo<IdentityServer4.Models.Client>(client);
                },
                optionsFactory: () => new DistributedCacheEntryOptions()
                {
                    AbsoluteExpirationRelativeToNow = Options.Caching.ClientStoreExpiration
                },
                considerUow: true);

        }
    }
}
